<template>
  <div class="user-manage-container">
    <el-card class="header">
        <div class="header-content">
            <div class="search">
                <span>管理员名搜索</span>
                <el-input v-model="nameSearch" class="input"></el-input>
                <el-button @click="handleSearch" type="primary">搜索</el-button>
            </div>
             <el-button type="primary"  @click="onAddAdmin">{{
          $t('msg.excel.addadministrators')
        }}</el-button>
        </div>
      </el-card>
    <el-card>
      <el-table :data="tableData" style="width: 100%" border >
        <!-- 序列号 -->
        <el-table-column label="#" type="index" align="center" />
        <!-- 姓名 -->
        <el-table-column :label="$t('msg.excel.name')" prop="name" align="center"/>
        <!-- 联系方式 -->
        <el-table-column :label="$t('msg.excel.mobile')" prop="phone" align="center" />
        <!-- 头像 -->
        <!-- <el-table-column :label="$t('msg.excel.avatar')" align="center">
          <template #default="{ row }">
            <el-image
              class="avatar"
              :src="row.avatar"
              :preview-src-list="[row.avatar]"
            />
          </template>
        </el-table-column> -->
        <!-- 工号 -->
        <el-table-column :label="$t('msg.excel.workNumber')" prop="workNumber" align="center"/>
        <!-- 年龄 -->
        <el-table-column :label="$t('msg.excel.age')" prop="age" align="center"/>
        <!-- 角色 -->
        <el-table-column :label="$t('msg.excel.role')" align="center">
          <template #default="{ row }">
            <div v-if="row.role">
              <el-tag 
                size="mini" 
                :type="row.role == '老板' ? 'warning' : ''"
              >{{
                row.role
              }}</el-tag>
            </div>
            <div v-else>
              <el-tag size="mini">{{ $t('msg.excel.defaultRole') }}</el-tag>
            </div>
            <!-- <el-tag size="mini" :type="row.super == true ? 'warning' : ''" >{{ row.super == true ? '老板' : '员工'  }}</el-tag> -->
          </template>
        </el-table-column>
        <!-- 开通时间 -->
        <el-table-column :label="$t('msg.excel.openTime')" align="center">
          <template #default="{ row }">
            {{ getData(row.registrationTime) }}
          </template>
        </el-table-column>
        <!-- 操作 -->
        <el-table-column
          :label="$t('msg.excel.action')"
          fixed="right"
          width="260"
          align="center"
        >
          <template #default="{ row }">
            <el-button type="primary" size="mini" @click="onShowAdmin(row)">{{
              $t('msg.excel.show')
            }}</el-button>
            <el-button type="info" size="mini" @click="onShowRole(row)" v-if="store.getters.userInfo.role == '老板'">{{
              $t('msg.excel.showRole')
            }}</el-button>
            <el-button type="danger" size="mini" @click="onDeleteUser(row)">{{
              $t('msg.excel.remove')
            }}</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="pagination"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :current-page="page"
        :page-sizes="[2, 5, 10, 20]"
        :page-size="size"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>
  </div>
  <Dialog
    v-if="dialogFormVisible"
    :dialogVisible = dialogFormVisible
    :type = dialogType
    :adminFormInitial="adminFormInitial"
    @dialogShow="dialogShow"
    @Confirm="handleConfirm"
  />
  <roles-dialog 
    v-if="modelValue" 
    :modelValue = modelValue
    :userId = userId
    @updateModelValue = "updateModelValue" 
    @updateRole = "getAdminList"
  />
</template>

<script setup>
import { onMounted, ref, onActivated } from 'vue'
import {getAdminsInfo,deleteAdmin,registerAdmin} from '@/api/user-manage'
import { watchSwitchLang } from '@/utils/i18n'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useI18n } from 'vue-i18n'
import dayjs from 'dayjs'
import Dialog from './components/Dialog.vue'
import RolesDialog from './components/roles.vue'
import { useStore } from 'vuex'
// 存储表格数据
const tableData = ref([])
const total = ref(0)
const page = ref(1)
const size = ref(5)
const router = useRouter()
const i18n = useI18n()
const dialogFormVisible = ref(false)
const dialogType = ref('')
const adminFormInitial = ref()
const modelValue = ref(false)
const userId = ref('')
const store = useStore()
console.log(store.getters.userInfo.role,'store.getters.userInfo.rolestore.getters.userInfo.role')
// 名称搜索
const nameSearch = ref('')
// 调用接口,获取表格数据
const getAdminList = async () => {
  const result = await getAdminsInfo({
    page: page.value,
    pageSize: size.value
  })
  tableData.value = result.findData
  console.log(tableData.value,'tableData.value')
  // total.value = result.total
}
// page-size改变时触发
const handleSizeChange = (currentSize) => {
  size.value = currentSize
  getAdminList()
}
// current-page 改变时触发
const handleCurrentChange = (currentPage) => {
  page.value = currentPage
  getAdminList()
}
//   点击搜索时的回调函数
const handleSearch = async() =>{
  page.value = 1
     // 调用模糊搜索的接口
  const query = {
    name:nameSearch.value,
    page:page.value,
    pageSize:size.value
  }
  const data = await getAdminsInfo(query)
  tableData.value = data.findData
  total.value = data.findData.length
  // 修改分页器总数的显示，当输入框中搜索东西的时候，再这样修改
  if(nameSearch.value !== ''){
    total.value = data.findData.length
  }else{
    // 没有输入东西的时候，通过接口获取全部数据，再进行赋值
    const getData = await getAdminsInfo()
    total.value = getData.findData.length
  }
  nameSearch.value = ''
}
// 对时间戳样式进行转换
const getData = (n) =>{
  return dayjs(n).format('YYYY-MM-DD HH:mm:ss')
}
// 增加管理员操作
const onAddAdmin = () =>{
  dialogFormVisible.value = true
  dialogType.value = 'add'
}
// 展示用户信息
const onShowAdmin = (row) =>{
  dialogFormVisible.value = true
  adminFormInitial.value = row
  dialogType.value = 'show'
}
// 展示角色弹框
const onShowRole = (row) =>{
  userId.value = row._id
  modelValue.value = true
}
// 角色弹框关闭的回调
const updateModelValue = (value) =>{
  modelValue.value = value
}
// 弹框关闭时
const dialogShow =(isShow) =>{
  dialogFormVisible.value = isShow
}
// 子组件点击确定时的回调函数
const handleConfirm = async (value,type) =>{
    const userInfo = {
        ...value,
        age:Number(value.age),
    }
    // 调用创建鲜花接口
    await registerAdmin(userInfo)
    ElMessage({
      type: 'success',
      message: i18n.t('msg.excel.addSuccess')
    })
    // 重新获取鲜花信息
    getAdminList()
    // 获取全部的数据，返回给total
    const getData = await getAdminsInfo()
    total.value = getData.findData.length
}
// 删除操作
const onDeleteUser = (row) => {
  if(row.super == true){
    ElMessage({
      type: 'warning',
      message: `${row.name}不可被删除！！`
    })
    return
  }
  ElMessageBox.confirm(
    i18n.t('msg.excel.dialogTitle1') +
      row.name +
      i18n.t('msg.excel.dialogTitle2'),
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    await deleteAdmin({id:row._id})
    ElMessage({
      type: 'success',
      message: i18n.t('msg.excel.removeSuccess')
    })
    getAdminList()
  })
}
// 监听语言切换
watchSwitchLang(getAdminList)
/**
 *  调用时机为首次挂载
 *  以及每次从缓存中被重新插入时
 * 处理导入用户后数据不重新加载的问题
 */
onActivated(getAdminList)
onMounted(async() => {
  getAdminList()
  // 获取全部的数据，返回给total
  const getData = await getAdminsInfo()
  total.value = getData.findData.length
})
</script>

<style lang="scss" scoped>
.user-manage-container {
  .header {
      margin-bottom: 22px;
      text-align: right;
      .header-content{
        display: flex;
        justify-content: space-between;
        align-items: center;
        .search{
            display: flex;
            align-items: center;
            width: 50%;
            .input{
                width: 30%;
                margin: 0 10px;
            }
        }
      }
    }
  :deep(.el-image) {
    width: 60px;
    height: 60px;
    border-radius: 50%;
  }

  :deep(.el-tag) {
    margin-right: 6px;
  }

  .pagination {
    margin-top: 20px;
    text-align: center;
  }
}
</style>
